//
//  FilterContentCell.m
//  OfficeBook
//
//  Created by 朱 琳 on 15/10/2.
//  Copyright (c) 2015年 sunny. All rights reserved.
//

#import "FilterFavorViewCell.h"

NSInteger const kItemNumInRow        =      3;     //每行个数
NSInteger  ButtonTagBaseOffset       =    500;

@interface FilterFavorViewCell()

@property (nonatomic, assign) UIEdgeInsets itemMargin;

@end

@implementation FilterFavorViewCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    return self;
}

-(void)buttonTapped:(UIButton *)button{
    button.selected = !button.selected;
    button.layer.borderColor = (button.selected? [UIColor colorWithHexString:@"#fd3935"]: [UIColor blackColor]).CGColor;
    
}

@synthesize favorItems = _favorItems;
-(void)setFavorItems:(NSArray *)favorItems {
    _favorItems = favorItems;
    
    if (favorItems.count == 0) {
        return;
    }
    
    self.itemMargin = UIEdgeInsetsMake(10, 10, 10, 10);
    CGFloat buttonWidth = (self.cellSize.width - self.itemMargin.left * (kItemNumInRow + 1)) / kItemNumInRow;
    NSUInteger itemColumnNum = (favorItems.count - 1) / kItemNumInRow + 1;
    CGFloat buttonHeight = (self.cellSize.height - self.itemMargin.top * (itemColumnNum + 1)) / itemColumnNum;
    
    [favorItems enumerateObjectsUsingBlock:^(id item, NSUInteger idx, BOOL *stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor clearColor];
        button.tag = ButtonTagBaseOffset + idx;  // !!tag
        [self.contentView addSubview:button];
        
        [button setTitle:item forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithHexString:@"#fd3935"] forState:UIControlStateSelected];
        button.layer.cornerRadius = 4.f;
        button.layer.borderWidth = 0.5f;
        
        NSUInteger rowIdx    = idx % kItemNumInRow;
        NSUInteger columnIdx = idx / kItemNumInRow;
        CGFloat buttonX = (rowIdx + 1) * self.itemMargin.left + rowIdx * buttonWidth;
        CGFloat buttonY = (columnIdx + 1) * self.itemMargin.top + columnIdx * buttonHeight;
        button.frame = CGRectMake(buttonX, buttonY, buttonWidth, buttonHeight);
        
        [button addTarget:self action:@selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside];
    }];
}

@end
